<?php

namespace App\Cache;

use App\Common\DataConvert;
use App\Common\Rsa;

class TokenCache extends Cache
{
    /**
     * @var string 缓存前缀
     */
    public static string $prefix = 'auth_token_';

    /**
     * 过期时间
     */
    const EXPIRE_TIME = 86400; // 1 day

    /**
     * 剩余过期时间多少时刷新缓存
     */
    const SURPLUS_TIME = 3600; // 1 hour

    public function getInfo(string $token): ?array
    {
        $nowTime = time();
        $val = $this->get(static::$prefix . $token);
        if ($val === false) {
            return null;
        }

        $data = DataConvert::decode(Rsa::getInstance()->privDecrypt($val));
        // 两天时间缓存失效
        if ($data['create_time'] + self::EXPIRE_TIME <= $nowTime) {
            $this->remove($token);
            return null;
        }

        // 1小时以内重置缓存
        if (($nowTime - $data['create_time']) <= self::SURPLUS_TIME) {
            $data['create_time'] = $nowTime;
            $this->createToken($data);
        }

        return $data;
    }

    /**
     * Notes: 创建或更新token
     * @param array $data
     * @return string
     */
    public function createToken(array $data): string
    {
        $data['create_time'] = time();
        $encrypt = Rsa::getInstance()->publicEncrypt(DataConvert::encode($data));

        $token = $data['id'] . '-' . md5(static::$prefix . $data['id']);
        $this->set(
            static::$prefix. $token,
            $encrypt,
            self::EXPIRE_TIME
        );
        return $token;
    }

    /**
     * 删除缓存
     * @param string $token
     * @return int
     */
    public function remove(string $token): int
    {
        return $this->del(static::$prefix. $token);
    }
}